<?php

namespace App\Jobs;

use App\Models\Mint;
use App\Services\DogecoinService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class TransferJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(public Mint $mint)
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if (!$this->mint->user->address || $this->mint->status != 'waiting') {
            return;
        }

        $this->mint->status = 'processing';
        $this->mint->save();
        try {
            $service = new DogecoinService();
            $tx = $service->transfer($this->mint->user->address, $this->mint->to_amount);
            $this->mint->hash = $tx;
            $this->mint->status = 'finished';
            $this->mint->save();
            logger('===============transfer doge success=====================');
            logger("doge transfer:" . json_encode($this->mint->toArray()));
            logger('===============transfer doge success=====================');
        } catch (\Throwable $e) {
            Log::error('===============withdraw err=====================');
            Log::error("doge transfer:" . json_encode($this->mint->toArray()));
            Log::error('===============withdraw err=====================');
            Log::error($e);
        }
    }
}
